const http = require('http')
const cheerio = require('cheerio')
const path = require('path')
const fs = require('fs')
const dirpath = path.join(__dirname, 'pics')

// 事件
process.on('message', url => {
  // 标识
  // 数据抓取
  http.get(url, res => {
    let html = ''
    res.on('data', chunk => html += chunk)
    res.on('end', async () => {
      // 把当前html内容，使用cheerio来完成选择加载
      const $ = cheerio.load(html)
      const imgs = $('.g-box-1200 > .picbz > li > a > img')
      imgs.each((index, el) => {
        let src = $(el).attr('src')
        if (src) {
          http.get(src, ret => {
            let name = path.basename(src)
            ret.pipe(fs.createWriteStream(dirpath + '/' + name))
            // process.send('11')
          })
        }
      })
    })
  })
})